package com.neoCalf.neoNotify.coreService;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.neoCalf.neoCommon.model.RabbitMqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.CompletableFuture;


/**
 * @author 小牛
 * @version 1.0
 * @description 消息发送服务类
 * @date 2025/6/30 22:16
 */
@Service
@Slf4j
public class MqSenderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 同步确认发送模式
    public void sendCheckCodeWithConfirm(RabbitMqMessage<Object> rabbitMqMessage) {
        sendCodeWithConfirm(JSON.toJSONString(rabbitMqMessage), "sendCheckCodeQueue");
    }

    public void sendCodeWithConfirm(String msg, String key) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(
                "",
                key,
                msg,
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setHeader("version", "1.0");
                    return message;
                },
                correlationData
        );
        CompletableFuture<CorrelationData.Confirm> future = correlationData.getFuture().completable();
        future.whenComplete((confirm, throwable) -> {
            if (confirm != null && confirm.isAck()) {
                log.info("消息成功到达Broker，消息ID：{}", correlationData.getId());
            } else {
                log.error("消息投递失败，ID：{}，原因：{}", correlationData.getId(), throwable != null ? throwable.getMessage() : "NACK");
            }
        });
    }

    // 异步回调处理
    @PostConstruct
    public void initCallback() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                // 实现消息补偿逻辑
                System.err.println("消息投递失败: " + cause);
            }
        });
    }
}
